<template>
  <div class="service-provider-search">
    <div class="search-bar">
      <input
          type="text"
          @input="handleInput"
          :value="formattedDisplayValue"
          placeholder="服务提供商"
          class="search-input"
      />
      <button @click="openPopup" class="search-button">...</button>
      <a href="#" class="contact-link">联系人</a>
      <a href="#" class="address-link">地址</a>
    </div>
    <div class="language-selector">
      <select v-model="selectedLanguage">
        <option value="en">英语</option>
        <option value="zh">中文</option>
      </select>
    </div>

    <!-- 弹出窗体 -->
    <div v-if="showPopup" class="popup">
      <div class="popup-content">
        <h3>搜索和选择服务提供商</h3>
        <div class="search-bar">
          <input
              v-model="searchQuery"
              placeholder="搜索..."
              class="search-input"
              @keyup.enter="handleSearch"
          />
          <button @click="handleSearch" class="search-button">搜索</button>
        </div>

        <div v-if="isLoading" class="loading">加载中...</div>

        <div v-else-if="searchResults.length" class="table-container">
          <table class="search-results">
            <thead>
            <tr>
              <th v-for="field in visibleFields" :key="field">
                {{ field }}
                <button @click="sortBy(field)" class="sort-button">
                  {{ field === sortField ? (sortOrder === 'asc' ? '↑' : '↓') : '↕' }}
                </button>
              </th>
              <th v-if="isMultiSelect">选择</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="item in paginatedResults"
                :key="getItemKey(item)"
                @click="handleItemClick(item)"
                @dblclick="handleItemDoubleClick(item)"
                :class="{ 'selected': isItemSelected(item) }">
              <td v-for="field in visibleFields" :key="field">
                {{ item[field] }}
              </td>
              <td v-if="isMultiSelect">
                <input
                    type="checkbox"
                    :checked="isItemSelected(item)"
                    @change="toggleItemSelection(item)"
                >
              </td>
            </tr>
            </tbody>
          </table>
        </div>
        <div v-else-if="searchPerformed" class="no-results">没有找到匹配的结果</div>

        <!-- 分页控件 -->
        <div v-if="searchResults.length" class="pagination">
          <span>{{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, totalItems) }} 共 {{ totalItems }} 条</span>
          <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
          <span>{{ currentPage }} / {{ totalPages }}</span>
          <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
          <select v-model="pageSize" @change="handlePageSizeChange">
            <option :value="10">10 条/页</option>
            <option :value="20">20 条/页</option>
            <option :value="30">30 条/页</option>
          </select>
        </div>

        <!-- 字段选择器 -->
        <div v-if="isMultiSelect" class="field-selector">
          <h4>显示字段：</h4>
          <div class="field-options">
            <label v-for="field in allFields" :key="field" class="field-option">
              <input
                  type="checkbox"
                  :checked="visibleFields.includes(field)"
                  @change="toggleField(field)"
              >
              {{ field }}
            </label>
          </div>
        </div>

        <!-- 已选项目 -->
        <div v-if="isMultiSelect && selectedItems.length" class="selected-items">
          <h4>已选择项目</h4>
          <ul>
            <li v-for="item in selectedItems" :key="getItemKey(item)">
              {{ getItemDisplayValue(item) }}
              <button @click="removeSelectedItem(item)" class="remove-button">移除</button>
            </li>
          </ul>
        </div>

        <div class="popup-buttons">
          <button @click="confirmSelection" class="confirm-button">确认</button>
          <button @click="closePopup" class="cancel-button">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue';

export default {
  name: 'ServiceProviderSearch',
  props: {
    modelValue: {
      type: Object,
      default: () => ({})
    },
    searchConfig: {
      type: Object,
      required: true,
      validator: (obj) => {
        return obj && obj.url && obj.keyField && obj.displayField && obj.token;
      }
    },
    isMultiSelect: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const multiSelectMode = computed(() => props.isMultiSelect);
    const selectedLanguage = ref('en');
    const showPopup = ref(false);
    const searchQuery = ref('');
    const searchResults = ref([]);
    const selectedItems = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(0);
    const sortField = ref('');
    const sortOrder = ref('asc');
    const isLoading = ref(false);
    const searchPerformed = ref(false);
    const displayValue = ref('');
    const totalPages = ref(1);

    const formattedDisplayValue = computed(() => {
      if (props.isMultiSelect) {
        if (Array.isArray(props.modelValue)) {
          const delimiter = props.searchConfig.delimiter || ', ';
          if (props.searchConfig.textshowField) {
            return props.modelValue.map(item => item[props.searchConfig.textshowField]).join(delimiter);
          } else {
            const displayFields = props.searchConfig.displayField.split(';');
            return props.modelValue.map(item =>
                displayFields.map(field => item[field]).filter(Boolean).join(' - ')
            ).join(delimiter);
          }
        }
        return '';
      } else {
        if (props.modelValue && typeof props.modelValue === 'object') {
          if (props.searchConfig.textshowField && props.modelValue[props.searchConfig.textshowField]) {
            return props.modelValue[props.searchConfig.textshowField];
          }
          const displayFields = props.searchConfig.displayField.split(';');
          return displayFields.map(field => props.modelValue[field]).filter(Boolean).join(' - ');
        }
        return displayValue.value;
      }
    });

    const handleInput = (event) => {
      const inputValue = event.target.value;
      displayValue.value = inputValue;
      if (props.searchConfig.textshowField) {
        emit('update:modelValue', { [props.searchConfig.textshowField]: inputValue });
      } else {
        emit('update:modelValue', { [props.searchConfig.displayField.split(';')[0]]: inputValue });
      }
    };

    const confirmSelection = () => {
      if (selectedItems.value.length === 0) {
        console.warn('No items selected');
        return;
      }

      if (props.isMultiSelect) {
        if (props.searchConfig.textshowField) {
          const delimiter = props.searchConfig.delimiter || ', ';
          const selectedValues = selectedItems.value.map(item => item[props.searchConfig.textshowField]);
          emit('update:modelValue', selectedItems.value);
          displayValue.value = selectedValues.join(delimiter);
        } else {
          emit('update:modelValue', selectedItems.value);
        }
      } else {
        const selectedItem = selectedItems.value[0];
        if (props.searchConfig.textshowField) {
          emit('update:modelValue', {
            ...selectedItem,
            [props.searchConfig.textshowField]: selectedItem[props.searchConfig.textshowField]
          });
        } else {
          emit('update:modelValue', selectedItem);
        }
      }
      closePopup();
    };


    const allFields = computed(() => props.searchConfig.displayField.split(';'));
    const visibleFields = ref(allFields.value);
    const keyFields = computed(() => props.searchConfig.keyField.split(';'));

    const paginatedResults = computed(() => {
      return searchResults.value;
    });


    const getItemKey = (item) => {
      return keyFields.value.map(field => item[field]).join('_');
    };

    const getItemDisplayValue = (item) => {
      return visibleFields.value.map(field => `${field}: ${item[field]}`).join(', ');
    };

    const isItemSelected = (item) => {
      return selectedItems.value.some(selectedItem => getItemKey(selectedItem) === getItemKey(item));
    };

    const openPopup = () => {
      showPopup.value = true;
      searchQuery.value = '';
      searchResults.value = [];
      searchPerformed.value = false;
    };

    const closePopup = () => {
      showPopup.value = false;
    };



    const handleSearch = async () => {
      if (!props.searchConfig || !props.searchConfig.url) {
        console.error('searchConfig or searchConfig.url is undefined');
        return;
      }

      isLoading.value = true;
      searchPerformed.value = true;
      try {
        const fullUrl = `${props.searchConfig.url}&query=${encodeURIComponent(searchQuery.value)}&pageNo=${currentPage.value}&pageSize=${pageSize.value}`;
        const headers = new Headers({
          'X-Access-Token': props.searchConfig.token
        });

        const response = await fetch(fullUrl, {
          method: 'GET',
          headers: headers
        });

        if (!response.ok) {
          throw new Error('搜索请求失败');
        }
        const data = await response.json();

        if (data.success && data.result) {
          searchResults.value = data.result.records;
          currentPage.value = data.result.current;
          totalItems.value = data.result.total;
          pageSize.value = data.result.size;
          totalPages.value = Math.ceil(totalItems.value / pageSize.value);
          console.log('Updated searchResults:', searchResults.value); // 添加日志
        } else {
          throw new Error(data.message || '搜索失败');
        }
      } catch (error) {
        console.error('搜索出错:', error);
        searchResults.value = [];
        totalItems.value = 0;
      } finally {
        isLoading.value = false;
      }
    };

    const sortBy = (field) => {
      if (sortField.value === field) {
        sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
      } else {
        sortField.value = field;
        sortOrder.value = 'asc';
      }
      searchResults.value.sort((a, b) => {
        if (a[field] < b[field]) return sortOrder.value === 'asc' ? -1 : 1;
        if (a[field] > b[field]) return sortOrder.value === 'asc' ? 1 : -1;
        return 0;
      });
    };

    const toggleField = (field) => {
      const index = visibleFields.value.indexOf(field);
      if (index > -1) {
        visibleFields.value.splice(index, 1);
      } else {
        visibleFields.value.push(field);
      }
    };

    const toggleItemSelection = (item) => {
      if (multiSelectMode.value) {
        const index = selectedItems.value.findIndex(selectedItem => getItemKey(selectedItem) === getItemKey(item));
        if (index === -1) {
          selectedItems.value.push(item);
        } else {
          selectedItems.value.splice(index, 1);
        }
      } else {
        selectedItems.value = [item];
        confirmSelection();
      }
    };


    const handleItemClick = (item) => {
      if (!props.isMultiSelect) {
        selectedItems.value = [item];
      }
    };

    const handleItemDoubleClick = (item) => {
      if (!props.isMultiSelect) {
        selectedItems.value = [item];
        confirmSelection();
      }
    };



    const removeSelectedItem = (item) => {
      const index = selectedItems.value.findIndex(selectedItem => getItemKey(selectedItem) === getItemKey(item));
      if (index !== -1) {
        selectedItems.value.splice(index, 1);
      }
    };


    const selectItem = (item) => {
      if (props.isMultiSelect) {
        toggleItemSelection(item);
      } else {
        selectedItems.value = [item];
      }
    };

    // 修改 prevPage 和 nextPage 函数
    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
        handleSearch();
      }
    };

    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
        handleSearch();
      }
    };
    const handlePageSizeChange = () => {
      currentPage.value = 1;
      handleSearch();
    };


    watch(() => props.modelValue, (newValue) => {
      if (props.isMultiSelect) {
        if (Array.isArray(newValue)) {
          const delimiter = props.searchConfig.delimiter || ', ';
          if (props.searchConfig.textshowField) {
            displayValue.value = newValue.map(item => item[props.searchConfig.textshowField]).join(delimiter);
          } else {
            const displayFields = props.searchConfig.displayField.split(';');
            displayValue.value = newValue.map(item =>
                displayFields.map(field => item[field]).filter(Boolean).join(' - ')
            ).join(delimiter);
          }
        } else {
          displayValue.value = '';
        }
      } else {
        if (newValue && typeof newValue === 'object') {
          if (props.searchConfig.textshowField && newValue[props.searchConfig.textshowField]) {
            displayValue.value = newValue[props.searchConfig.textshowField];
          } else {
            const displayFields = props.searchConfig.displayField.split(';');
            displayValue.value = displayFields.map(field => newValue[field]).filter(Boolean).join(' - ');
          }
        } else {
          displayValue.value = '';
        }
      }
    }, { immediate: true });
    return {
      selectedLanguage,
      showPopup,
      searchQuery,
      searchResults,
      selectedItems,
      currentPage,
      pageSize,
      totalItems,
      sortField,
      sortOrder,
      isLoading,
      searchPerformed,
      displayValue,

      allFields,
      visibleFields,
      paginatedResults,
      totalPages,
      openPopup,
      closePopup,
      formattedDisplayValue,
      handleInput,
      confirmSelection,
      handleSearch,
      getItemKey,
      getItemDisplayValue,
      isItemSelected,
      removeSelectedItem,

      prevPage,
      nextPage,
      sortBy,
      toggleField,
      handlePageSizeChange,
      toggleItemSelection,
      selectItem,
      handleItemClick,
      handleItemDoubleClick,

      multiSelectMode
    };
  }
};
</script>

<style scoped>
.service-provider-search {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.search-bar {
  display: flex;
  align-items: center;
  flex-grow: 1;
  max-width: 400px;
}

.search-input {
  flex-grow: 1;
  padding: 4px 8px;
  border: 1px solid #ced4da;
  border-radius: 4px 0 0 4px;
  font-size: 14px;
}

.search-button {
  padding: 4px 8px;
  background-color: #007bff;
  color: white;
  border: 1px solid #007bff;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  font-size: 14px;
}

.contact-link, .address-link {
  margin-left: 15px;
  color: #007bff;
  text-decoration: none;
  font-size: 14px;
}

.language-selector {
  margin-left: auto;
}

.language-selector select {
  padding: 4px 8px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
}

.popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.popup-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 80%;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
}

.table-container {
  max-height: 300px;
  overflow-y: auto;
}

.search-results {
  width: 100%;
  border-collapse: collapse;
}

.search-results th, .search-results td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.search-results th {
  background-color: #f2f2f2;
  position: sticky;
  top: 0;
}

.sort-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0 5px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}

.pagination button, .pagination select {
  margin: 0 5px;
  padding: 5px 10px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
}

.field-selector {
  margin-top: 10px;
}

.field-options {
  display: flex;
  flex-wrap: wrap;
}

.field-option {
  margin-right: 10px;
  margin-bottom: 5px;
}

.selected-items {
  margin-top: 10px;
}

.selected-items ul {
  list-style-type: none;
  padding: 0;
}

.selected-items li {
  margin-bottom: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.remove-button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 2px 5px;
  border-radius: 3px;
  cursor: pointer;
}

.popup-buttons {
  margin-top: 20px;
  text-align: right;
}

.confirm-button, .cancel-button {
  padding: 8px 15px;
  margin-left: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-button {
  background-color: #4CAF50;
  color: white;
}

.cancel-button {
  background-color: #f44336;
  color: white;
}

.loading, .no-results {
  text-align: center;
  padding: 20px;
  color: #666;
}

.search-results tr.selected {
  background-color: #e6f7ff;
}

.search-results tr:hover {
  background-color: #f5f5f5;
  cursor: pointer;
}
</style>
